#! /usr/bin/env python
#coding=utf-8
import wx
import wx.lib.masked as masked
import wx.grid as grid
import Tms

#todo: add ability to email students about upcoming talks, and send out schedules.
class StudentFrame(wx.Frame):
    """The Main window thats seen at startup""" 
    def __init__(self, parent, *args, **kwargs):
        wx.Frame.__init__(self, parent, *args, **kwargs)
        self.p = parent
        #self.db = parent.db
        
        self.notebookStarted = False
        self.TalkHistoryItem = 0
        self.StudyHistoryItem = 0
        self.SettingHistoryItem = 0
        self.Bind(wx.EVT_CLOSE, self.On_Student_Close)
        self.newStudent = False
        self.talksMaleServant = ['Talk H','Talk 1','Talk 3','Reader', 'CBS Conductor']
        self.talksMale = ['Talk 1','Talk 3','Reader']
        self.talksFemale = ['Talk 2','Talk 3','Assist']

        # Add the Front Panel with Tabs
        self.StudentPanel = wx.Panel(self)
        self.StudentNB = wx.Notebook(self.StudentPanel, wx.ID_ANY, pos=(155,3), size=(475,420), style=wx.NB_TOP)
        self.StudentNB.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.on_StudentNB_change)
        self.StudentNB_PersonalTab = wx.Panel(self.StudentNB, wx.ID_ANY, style=wx.TAB_TRAVERSAL)
        self.StudentNB.AddPage(page=self.StudentNB_PersonalTab, select=True, text='Personal Info')
        self.StudentNB_TalkHistTab = wx.Panel(self.StudentNB, wx.ID_ANY, style=wx.TAB_TRAVERSAL)
        self.StudentNB.AddPage(page=self.StudentNB_TalkHistTab, select=False, text='Talk History')
        self.StudentNB_StudyHistTab = wx.Panel(self.StudentNB, wx.ID_ANY, style=wx.TAB_TRAVERSAL)
        self.StudentNB.AddPage(page=self.StudentNB_StudyHistTab, select=False, text='Study History')
        self.StudentNB_SettingHistTab = wx.Panel(self.StudentNB, wx.ID_ANY, style=wx.TAB_TRAVERSAL)
        self.StudentNB.AddPage(page=self.StudentNB_SettingHistTab, select=False, text='Setting History')
        
        #get a list of students

        #Setup Buttons for Student Panel
        self.lstStudent = wx.ListBox(self.StudentPanel, id=wx.ID_ANY, size=(150,420), pos=(0,3), choices=[], style=wx.LB_HSCROLL|wx.LB_NEEDED_SB|wx.LB_SORT|wx.LB_SINGLE)
        self.lstStudent.Bind(wx.EVT_LISTBOX, self.On_lstStudent_select)
        self.btnBack = wx.Button(self.StudentPanel, label="<<<< Back", pos=(37,428))
        self.btnBack.Bind(wx.EVT_BUTTON, self.On_Back_btn)
        self.btnSave = wx.Button(self.StudentPanel,wx.ID_ANY,pos=(165,428),label="Save Changes")
        self.btnSave.Bind(wx.EVT_BUTTON, self.On_Save_btn)
        self.btnCancel = wx.Button(self.StudentPanel,wx.ID_ANY,pos=(257,428),label="Cancel Changes")
        self.btnCancel.Bind(wx.EVT_BUTTON, self.on_btnCancel_select)
        self.btnAddStudent = wx.Button(self.StudentPanel, pos=(357,428), label="Add New Student")
        self.btnAddStudent.Bind(wx.EVT_BUTTON, self.on_btnAddStudent_select)
        self.btnDeleteStudent = wx.Button(self.StudentPanel, pos=(464,428), label="Delete Student")
        self.btnDeleteStudent.Bind(wx.EVT_BUTTON, self.on_btnDeleteStudent_select)

        #Personal Info tab
        self.ckbxActive = wx.CheckBox(self.StudentNB_PersonalTab, pos=(5,5), label="Student Active in the TMS?:", style=wx.ALIGN_RIGHT)
        sttxtLastName = wx.StaticText(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(5,25), label="Last Name:")
        self.txtLastName = wx.TextCtrl(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(5,40), size=(125,-1))
        sttxtFirstName = wx.StaticText(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(135,25), label="First Name:")
        self.txtFirstName = wx.TextCtrl(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(135,40), size=(105,-1))
        sttxtScreenName = wx.StaticText(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(245,25), label="Screen Name:")
        self.txtScreenName = wx.TextCtrl(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(245,40), size=(220,-1))
        sttxtSex = wx.StaticText(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(5,65), label="Sex:")
        self.choiceSex = wx.Choice(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(5,80), choices=['Male','Female'])
        self.choiceSex.Bind(wx.EVT_CHOICE, self.on_choiceSex_select)
        sttxtPhone = wx.StaticText(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(75,65), label="Phone #:")
        self.txtPhone = masked.TextCtrl(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(75,80), size=(110,-1), mask="(###) ###-####")
        sttxtEmail = wx.StaticText(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(190,65), label="Email:")
        self.txtEmail = wx.TextCtrl(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(190,80), size=(145,-1))
        self.ckbxServant = wx.CheckBox(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(345,82), label="Servant:", style=wx.ALIGN_RIGHT)
        self.ckbxServant.Bind(wx.EVT_CHECKBOX, self.on_ckbxServant_select)
        sttxtUseWhere = wx.StaticText(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(5,105), label="Use Where:")
        self.cklstbxUseWhere = wx.CheckListBox(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(5,120), size=(85,35), choices=['Main School', 'Aux School'])
        sttxtTalkAvailability = wx.StaticText(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(105,105), label="Talk Availability:")
        self.cklstbxTalkAvailability = wx.CheckListBox(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(105,120), size=(125,65), choices=['Talk H', 'Talk 1', 'Talk 3'])
        sttxtRemarks = wx.StaticText(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(5,180), label="Remarks:")
        self.txtRemarks = wx.TextCtrl(self.StudentNB_PersonalTab, wx.ID_ANY, pos=(5,200), size=(460,190), style=wx.TE_MULTILINE)
        
        #Talk History Tab
        self.lstTalkHistory = grid.Grid(self.StudentNB_TalkHistTab, pos=(5,5), size=(455,200))
        self.lstTalkHistory.Bind(grid.EVT_GRID_SELECT_CELL, self.on_lstTalkHistory_select)
        self.lstTalkHistory.CreateGrid(0,5)
        self.lstTalkHistory.SetColLabelValue(0, 'Date')
        self.lstTalkHistory.SetColLabelValue(1,'Talk')
        self.lstTalkHistory.SetColLabelValue(2,'Study')
        self.lstTalkHistory.SetColLabelValue(3,'Result')
        self.lstTalkHistory.SetColLabelValue(4,'Remarks')
        
        self.lstTalkHistory.SetColLabelSize(20)
        self.lstTalkHistory.SetRowLabelSize(0)
        self.lstTalkHistory.EnableEditing(False)
        
        self.btnTalkHistoryAdd = wx.Button(self.StudentNB_TalkHistTab, wx.ID_ANY, pos=(5,220), label="Add")
        self.btnTalkHistoryAdd.Bind(wx.EVT_BUTTON, self.on_TalkHistoryAdd_btn)
        self.btnTalkHistoryDelete = wx.Button(self.StudentNB_TalkHistTab, wx.ID_ANY, pos=(85,220), label="Delete")
        self.btnTalkHistoryDelete.Bind(wx.EVT_BUTTON, self.on_TalkHistoryDelete_btn)
        self.btnTalkHistorySave = wx.Button(self.StudentNB_TalkHistTab, wx.ID_ANY, pos=(165,220), label='Save')
        self.btnTalkHistorySave.Bind(wx.EVT_BUTTON, self.on_TalkHistorySave_btn)
        
        self.sttxtTalkHistoryDate = wx.StaticText(self.StudentNB_TalkHistTab, wx.ID_ANY, pos=(5,250), label="Date:")
        self.dateTalkHistory = wx.DatePickerCtrl(self.StudentNB_TalkHistTab, pos=(5,265), size=(95,20), style=wx.DP_DROPDOWN|wx.DP_SHOWCENTURY) #self.txtTalkHistoryDate = wx.TextCtrl(self.StudentNB_TalkHistTab, wx.ID_ANY, pos=(5,265), size=(70,20))
        self.sttxtTalkHistoryTalk = wx.StaticText(self.StudentNB_TalkHistTab, wx.ID_ANY, pos=(105,250), label="Talk:")
        self.cmbbxTalkHistoryTalk = wx.ComboBox(self.StudentNB_TalkHistTab, wx.ID_ANY, pos=(105,265), choices=['Highlights', 'Talk 1','Talk 2', 'Talk 3', 'Reader', 'Assist'])
        self.sttxtTalkHistoryResult = wx.StaticText(self.StudentNB_TalkHistTab,wx.ID_ANY, pos=(185,250), label="Result:")
        self.cmbbxTalkHistoryResult = wx.ComboBox(self.StudentNB_TalkHistTab,wx.ID_ANY, pos=(185,265),choices=['Completed','Cancelled','Fillin'])
        self.sttxtTalkHistoryStudy = wx.StaticText(self.StudentNB_TalkHistTab,wx.ID_ANY,pos=(270,250),label="Study:")
        self.cmbbxTalkHistoryStudy = wx.ComboBox(self.StudentNB_TalkHistTab, wx.ID_ANY,pos=(270,265),size=(195,-1),choices=Tms.studyNumber, style=wx.CB_READONLY)
        self.sttxtTalkHistoryRemarks = wx.StaticText(self.StudentNB_TalkHistTab,wx.ID_ANY,pos=(5,290),label="Remarks:")
        self.txtTalkHistoryRemarks = wx.TextCtrl(self.StudentNB_TalkHistTab, wx.ID_ANY, pos=(5,305), size=(460,85), style=wx.TE_MULTILINE)

        #Study History Tab
        self.lstStudyHistory = grid.Grid(self.StudentNB_StudyHistTab, wx.ID_ANY, pos=(5,5), size=(455,200))
        self.lstStudyHistory.Bind(grid.EVT_GRID_SELECT_CELL, self.on_lstStudyHistory_select)
        self.lstStudyHistory.CreateGrid(0,3)
        self.lstStudyHistory.SetColLabelValue(0, 'Study')
        self.lstStudyHistory.SetColLabelValue(1,'Assigned')
        self.lstStudyHistory.SetColLabelValue(2,'Completed')
        self.lstStudyHistory.SetColLabelSize(20)
        self.lstStudyHistory.DisableCellEditControl()
        self.lstStudyHistory.SetRowLabelSize(0)
        self.lstStudyHistory.EnableEditing(False)
        
        self.btnStudyHistoryAdd = wx.Button(self.StudentNB_StudyHistTab, wx.ID_ANY, pos=(5,220), label="Add")
        self.btnStudyHistoryAdd.Bind(wx.EVT_BUTTON, self.on_btnStudyHistoryAdd_select)
        self.btnStudyHistoryDelete = wx.Button(self.StudentNB_StudyHistTab, wx.ID_ANY, pos=(85,220), label="Delete")
        self.btnStudyHistoryDelete.Bind(wx.EVT_BUTTON, self.on_btnStudyHistoryDelete_select)
        self.btnStudyHistorySave = wx.Button(self.StudentNB_StudyHistTab, pos = (165,220), label='Save')
        self.btnStudyHistorySave.Bind(wx.EVT_BUTTON, self.on_btnStudyHistorySave_select)
        
        self.sttxtStudyHistoryStudy = wx.StaticText(self.StudentNB_StudyHistTab,wx.ID_ANY,pos=(5,250),label="Study:")
        self.cmbbxStudyHistoryStudy = wx.ComboBox(self.StudentNB_StudyHistTab, wx.ID_ANY,pos=(5,265),size=(240,-1),choices=Tms.studyNumber)
        self.sttxtStudyHistoryAssigned = wx.StaticText(self.StudentNB_StudyHistTab,wx.ID_ANY,pos=(250,250),label="Date Assigned:")
        self.dateStudyHistoryAssigned = wx.DatePickerCtrl(self.StudentNB_StudyHistTab, pos=(250,265), size=(105,-1), style=wx.DP_DROPDOWN|wx.DP_ALLOWNONE|wx.DP_SHOWCENTURY)
        self.sttxtStudyHistoryCompleted = wx.StaticText(self.StudentNB_StudyHistTab,wx.ID_ANY,pos=(360,250), label="Date Completed:")
        self.dateStudyHistoryCompleted = wx.DatePickerCtrl(self.StudentNB_StudyHistTab, pos=(360,265), size=(105,-1), style=wx.DP_DROPDOWN|wx.DP_ALLOWNONE|wx.DP_SHOWCENTURY)
        
        #Setting History Tab
        self.lstSettingHistory = grid.Grid(self.StudentNB_SettingHistTab, wx.ID_ANY, pos=(5,5), size=(455,200))
        self.lstSettingHistory.Bind(grid.EVT_GRID_SELECT_CELL, self.on_lstSettingHistory_select)
        self.lstSettingHistory.CreateGrid(0,2)
        self.lstSettingHistory.SetColLabelValue(0, 'Setting')
        self.lstSettingHistory.SetColLabelValue(1,'Date Used')
        self.lstSettingHistory.SetColLabelSize(20)
        self.lstSettingHistory.DisableCellEditControl()
        self.lstSettingHistory.SetRowLabelSize(0)
        self.lstSettingHistory.EnableEditing(False)
        
        self.btnSettingHistoryAdd = wx.Button(self.StudentNB_SettingHistTab, pos=(5,220), label="Add")
        self.btnSettingHistoryAdd.Bind(wx.EVT_BUTTON, self.on_btnSettingHistoryAdd_select)
        self.btnSettingHistoryDelete = wx.Button(self.StudentNB_SettingHistTab, pos=(85,220), label="Delete")
        self.btnSettingHistoryDelete.Bind(wx.EVT_BUTTON, self.on_btnSettingHistoryDelete_select)
        self.btnSettingHistorySave = wx.Button(self.StudentNB_SettingHistTab, pos=(165,220), label="Save")
        self.btnSettingHistorySave.Bind(wx.EVT_BUTTON, self.on_btnSettingHistorySave_select)

        self.sttxtSettingHistorySetting = wx.StaticText(self.StudentNB_SettingHistTab,wx.ID_ANY,pos=(5,250),label="Setting:")
        self.cmbbxSettingHistorySetting = wx.ComboBox(self.StudentNB_SettingHistTab, wx.ID_ANY,pos=(5,265),size=(350,-1),choices=Tms.settingNumber)
        self.sttxtSettingHistoryUsed = wx.StaticText(self.StudentNB_SettingHistTab,wx.ID_ANY,pos=(360,250), label="Date Used:")
        self.dateSettingHistoryUsed = wx.DatePickerCtrl(self.StudentNB_SettingHistTab, pos=(360,265), size=(105,-1), style=wx.DP_DROPDOWN|wx.DP_SHOWCENTURY)

        self.notebookStarted = True
        self.Center(wx.BOTH)
        Tms.loadStudentsList(self, 'Students')
        
        self.lstStudent.SetSelection(0)
        self.On_lstStudent_select()
        self.lstStudent.SetFocus()

    def on_StudentNB_change(self, event=None):
        """show or hide student buttons at bottom based upon which page you are on"""
        newpage = event.GetSelection()
        if self.notebookStarted==True and newpage != -1:
            label = self.StudentNB.GetPageText(newpage)
            if label == 'Personal Info':
                Tms.showPersonalInfoButtons(self, show=True)
            else:
                Tms.showPersonalInfoButtons(self, show=False)
        event.Skip()
        
    def On_Back_btn(self, event=None):
        """back button pressed, so close student window"""
        self.On_Student_Close()

    def On_Student_Close(self, event=None):
        self.p.Enable(True)
        self.p.SetFocus()
        if event == None:
            self.Close()
        else:
            event.Skip()

    def On_lstStudent_select(self, event=None):
        """A Student was selected from the list, so populate all tabs with student info"""
        Tms.loadStudentInfo(self, self.lstStudent.GetStringSelection())
        self.newStudent = False
    
    def on_lstTalkHistory_select(self, event=None):
        """item on grid was selected so display row items in text fields"""
        if self.lstTalkHistory.GetGridCursorRow() != -1: # make sure something was actually selected
            #show buttons
            Tms.showTalkHistoryButtons(self, show=True)
            
            self.TalkHistoryItem = row = event.GetRow()
            studID = Tms.GetStudentId(self, self.lstStudent.GetStringSelection())

            #get date from col0 and convert to Yr Mo & Day to set date field
            d = self.lstTalkHistory.GetCellValue(row, 0)
            Mo, Day, Yr = d.split('/')
            self.dateTalkHistory.SetValue(wx.DateTimeFromDMY(int(Day), int(Mo)-1, int(Yr)))
            
            self.cmbbxTalkHistoryTalk.SetValue(self.lstTalkHistory.GetCellValue(row,1))
            self.cmbbxTalkHistoryResult.SetValue(self.lstTalkHistory.GetCellValue(row,3))
            study = self.lstTalkHistory.GetCellValue(row,2)
            if study != '':
                self.cmbbxTalkHistoryStudy.SetSelection(int(study))
            else:
                self.cmbbxTalkHistoryStudy.SetSelection(0)
            self.txtTalkHistoryRemarks.SetValue(self.lstTalkHistory.GetCellValue(row,4))
            
        else:
            # nothing actually selected, so hide buttons
            Tms.showTalkHistoryButtons(self, show=False)        
        event.Skip()

    def on_lstStudyHistory_select(self, event=None):
        """item on grid was selected so display row items in text fields"""
        if self.lstStudyHistory.GetGridCursorRow() != -1: # make sure something was actually selected
            Tms.showStudyHistoryButtons(self, show=True)
            self.StudyHistoryItem = row = event.GetRow()
            studID = Tms.GetStudentId(self, self.lstStudent.GetStringSelection())
            study = self.lstStudyHistory.GetCellValue(row,0)
            if study != '':
                self.cmbbxStudyHistoryStudy.SetSelection(int(study))
            else:
                self.cmbbxStudyHistoryStudy.SetSelection(0)
            self.dateStudyHistoryAssigned.SetValue(Tms.convertGrid2wxDate(self.lstStudyHistory.GetCellValue(row,1)))
            self.dateStudyHistoryCompleted.SetValue(Tms.convertGrid2wxDate(self.lstStudyHistory.GetCellValue(row,2)))
        else:
            Tms.showStudyHistoryButtons(self, show=False)
        event.Skip()
    
    def on_lstSettingHistory_select(self, event=None):
        """item on grid was selected so display row items in text fields"""
        if self.lstSettingHistory.GetGridCursorRow() != -1: # make sure something was actually selected
            Tms.showSettingHistoryButtons(self, show=True)
            self.SettingHistoryItem = row = event.GetRow()
            studID = Tms.GetStudentId(self, self.lstStudent.GetStringSelection())
            setting = self.lstSettingHistory.GetCellValue(row,0)
            self.cmbbxSettingHistorySetting.SetSelection(int(setting))
            self.dateSettingHistoryUsed.SetValue(Tms.convertGrid2wxDate(self.lstSettingHistory.GetCellValue(row,1)))
        else:
            Tms.showSettingHistoryButtons(self, show=False)
        event.Skip()
        
    def On_Save_btn(self, event=None):
        """save the personal info of this individual"""
        screen = self.txtScreenName.GetValue()
        if screen == '':
            msg = wx.MessageDialog(self, 'You Must enter a ScreenName before you can save', style=wx.OK)
            msg.ShowModal()
            msg.Destroy()
            event.Skip()
            return
        
        if self.newStudent:
            dat = self.p.db.Students
            for id in range(1, 9999):
                if not id in dat:
                    studentID = id
                    dat[id] = {}
                    break
        else:
            student = self.lstStudent.GetStringSelection()
            studentID = Tms.GetStudentId(self, student)
        studentData = self.p.db.Students[studentID]

        studentData['Active'] = self.ckbxActive.GetValue()
        studentData['LastName'] = self.txtLastName.GetValue()
        studentData['FirstName'] = self.txtFirstName.GetValue()
        studentData['ScreenName'] = screen
        studentData['Sex'] = self.choiceSex.GetStringSelection()
        studentData['Phone'] = self.txtPhone.GetValue()
        studentData['Email'] = self.txtEmail.GetValue()
        if self.choiceSex.GetStringSelection() == 'Male':
            studentData['Servant'] = self.ckbxServant.GetValue()
        else: 
            studentData['Servant'] = False
        # save current items in Talk Availability
        for item in range(0, self.cklstbxTalkAvailability.GetCount()):
            label = self.cklstbxTalkAvailability.GetString(item)
            studentData[label] = self.cklstbxTalkAvailability.IsChecked(item)
        #save 'Use Where' info
        for item in range(0, self.cklstbxUseWhere.GetCount()):
            label = self.cklstbxUseWhere.GetString(item)
            studentData[label] = self.cklstbxUseWhere.IsChecked(item)
            
        studentData['Remarks'] = self.txtRemarks.GetValue()
        
        self.p.db.save()
        self.newStudent = False
        Tms.loadStudentsList(self, 'Students')
        self.lstStudent.SetStringSelection(self.txtScreenName.GetValue())
        Tms.loadStudentInfo(self, self.txtScreenName.GetValue())
        event.Skip()
        
    def on_btnCancel_select(self, event=None):
        if self.newStudent:
            self.lstStudent.SetSelection(0)
        student = self.lstStudent.GetStringSelection()
        studentID = Tms.GetStudentId(self, student)
        Tms.loadStudentInfo(self, student)
        event.Skip()
        
    def on_btnAddStudent_select(self, event=None):
        self.lstStudent.SetSelection(-1)
        self.newStudent = True
        self.ckbxActive.SetValue(True)
        self.txtLastName.SetValue('')
        self.txtFirstName.SetValue('')
        self.txtScreenName.SetValue('')
        self.choiceSex.SetStringSelection('Male')
        self.on_choiceSex_select()
        self.txtPhone.SetValue('')
        self.txtEmail.SetValue('')
        self.ckbxServant.Show(True)
        self.ckbxServant.SetValue(False)
        self.txtRemarks.SetValue('')
        self.cklstbxUseWhere.Check(0, True)
        self.cklstbxUseWhere.Check(1, True)
        event.Skip()
        
    def on_btnDeleteStudent_select(self, event=None):
        if not self.newStudent:
            msg = wx.MessageDialog(self, 'This will PERMANANTLY Delete this Students Record!, Press "Yes" to delete or "No" to keep this record', style=wx.YES_NO)
            if msg.ShowModal() == wx.ID_YES:
                student = self.lstStudent.GetStringSelection()
                studentID = Tms.GetStudentId(self, student)
                del self.p.db.Students[studentID]
                Tms.loadStudentsList(self, 'Students')
                self.lstStudent.SetSelection(0)
                student = self.lstStudent.GetStringSelection()
                Tms.loadStudentInfo(self, student)
            msg.Destroy()
        event.Skip()
        
    def on_choiceSex_select(self, event=None):
        if self.choiceSex.GetStringSelection()=='Male':
            self.ckbxServant.Show(True)
            if self.ckbxServant.GetValue():
                self.load_cklstbxTalkAvailability(self.talksMaleServant)
            else:
                self.load_cklstbxTalkAvailability(self.talksMale)
        else:
            self.ckbxServant.Show(False)
            self.load_cklstbxTalkAvailability(self.talksFemale)
        if not self.newStudent:
            Tms.restoreTalkAvailabilityValues(self)

        if event !=None: event.Skip()

    def on_ckbxServant_select(self, event=None):
        if self.ckbxServant.GetValue():
            talks = self.talksMaleServant
        else:
            talks = self.talksMale
        self.load_cklstbxTalkAvailability(talks)
        if not self.newStudent:
            Tms.restoreTalkAvailabilityValues(self)
        event.Skip()
        
    def on_TalkHistoryAdd_btn(self, event=None):
        # enable buttons to add new talk history item
        Tms.showTalkHistoryButtons(self, show=True)
        
        #clear all fields
        self.dateTalkHistory.SetValue(wx.DateTime_Now())
        self.cmbbxTalkHistoryTalk.SetValue("")
        self.cmbbxTalkHistoryResult.SetValue("")
        self.cmbbxTalkHistoryStudy.SetSelection(0)
        self.txtTalkHistoryRemarks.SetValue("")
        self.TalkHistoryItem = -2
        
    def on_TalkHistoryDelete_btn(self, event=None):
        """ Talk History Item has been requested to be deleted"""
        student = self.lstStudent.GetStringSelection()
        studentID = Tms.GetStudentId(self, student)
        if self.TalkHistoryItem > -1:
            #only delete if something has been selected
            try:
                self.p.db.TalkHistory[studentID].pop(self.lstTalkHistory.GetGridCursorRow()-1)
            except:
                print 'Removal of TalkHistory item failed!'
        self.p.db.save()
        Tms.loadStudentInfo(self, student)
        
    def on_TalkHistorySave_btn(self, event=None):
        """ Save Talk History Item """
        student = self.lstStudent.GetStringSelection()
        studentID = Tms.GetStudentId(self, student)
        if self.TalkHistoryItem != -1: #row number for item. -1 means nothing selected
            
            # collect items together for saving
            date = self.dateTalkHistory.GetValue().FormatISODate().split('-')
            talk = self.cmbbxTalkHistoryTalk.GetValue()
            result = self.cmbbxTalkHistoryResult.GetValue()
            study = self.cmbbxTalkHistoryStudy.GetSelection()
            remarks = self.txtTalkHistoryRemarks.GetValue()
            item = {'Date':date, 'Talk':talk, 'Result':result, 'Study':study, 'Remarks':remarks}
            if not studentID in self.p.db.TalkHistory:
                self.p.db.TalkHistory[studentID] = []
            if self.TalkHistoryItem == -2:
                # This item was just added, so append to current list
                self.p.db.TalkHistory[studentID].append(item)
            else:
                # find row to replace
                self.p.db.TalkHistory[studentID][self.TalkHistoryItem] = item
            self.p.db.save()
            Tms.loadStudentInfo(self, student)
        
    def on_btnStudyHistoryAdd_select(self, event=None):
#        global StudyHistoryItem
        Tms.showStudyHistoryButtons(self, show=True)
        self.cmbbxStudyHistoryStudy.SetSelection(0)
        self.dateStudyHistoryAssigned.SetValue(wx.DefaultDateTime)
        self.dateStudyHistoryCompleted.SetValue(wx.DefaultDateTime)
        
        self.StudyHistoryItem = -2
        event.Skip()
        
    def on_btnStudyHistoryDelete_select(self, event=None):
        student = self.lstStudent.GetStringSelection()
        studentID = Tms.GetStudentId(self, student)
        if self.StudyHistoryItem > -1:
            #only delete if something has been selected
            row = self.lstStudyHistory.GetGridCursorRow()
            study = int(self.lstStudyHistory.GetCellValue(row,0))
            del self.p.db.StudyHistory[studentID][study]
            self.p.db.save()
        Tms.loadStudentInfo(self, student)
        event.Skip()
        
    def on_btnStudyHistorySave_select(self, event=None):
        student = self.lstStudent.GetStringSelection()
        studentID = Tms.GetStudentId(self, student)
        if self.StudyHistoryItem != -1:
            # collect items together for saving
            study = int(self.cmbbxStudyHistoryStudy.GetSelection())
            assigned = Tms.convertwxDate2fileFormat(self.dateStudyHistoryAssigned.GetValue())
            if study == 0 or assigned == None:
                event.Skip()
                return
            completed = Tms.convertwxDate2fileFormat(self.dateStudyHistoryCompleted.GetValue())
            item = {'Assigned':assigned, 'Completed':completed}
            
            sHist = self.p.db.StudyHistory
            if studentID in sHist:
                sHist[studentID][study]=item
            else:
                sHist[studentID] = {study:item}
                
            self.p.db.save()
        Tms.loadStudentInfo(self, student)
        event.Skip()
        
    def on_btnSettingHistoryAdd_select(self, event=None):
        Tms.showSettingHistoryButtons(self, show=True)
        self.cmbbxSettingHistorySetting.SetSelection(0)
        self.dateSettingHistoryUsed.SetValue(wx.DateTime_Now())

        self.SettingHistoryItem = -2
        event.Skip()
        
    def on_btnSettingHistoryDelete_select(self, event=None):
        student = self.lstStudent.GetStringSelection()
        studentID = Tms.GetStudentId(self, student)
        if self.SettingHistoryItem > -1: #only delete if something has been selected
            row = self.lstSettingHistory.GetGridCursorRow()
            setting = int(self.lstSettingHistory.GetCellValue(row,0))
            del self.p.db.SettingHistory[studentID][setting]
            self.p.db.save()
        Tms.loadStudentInfo(self, student)
        event.Skip()
        
    def on_btnSettingHistorySave_select(self, event=None):
        student = self.lstStudent.GetStringSelection()
        studentID = Tms.GetStudentId(self, student)
        if self.SettingHistoryItem != -1:
            # collect items together for saving
            setting = self.cmbbxSettingHistorySetting.GetSelection()
            date = Tms.convertwxDate2fileFormat(self.dateSettingHistoryUsed.GetValue())
            if setting == 0 or date == None:
                Tms.loadStudentInfo(self, student)
                event.Skip()
                return
            item = {setting:date}
            sH = self.p.db.SettingHistory
            if studentID in sH:
                sH[studentID][setting] = date
            else:
                sH[studentID] = item
            self.p.db.save()
        Tms.loadStudentInfo(self, student)
        event.Skip()
        
    def load_cklstbxTalkAvailability(self, list):
        box = self.cklstbxTalkAvailability
        box.Clear()
        for item in list:
            box.Append(item)
    
if __name__ == '__main__':
    Tms.Main()
